package com.movie.modules.jf.controller;

import com.movie.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author JF-PJJ
 */
@RestController
@Api(tags = "上传文件",value = "前后台通用")
public class FileController {

    @Value("${filepath.upload}")
    private String filePath;

    @PostMapping("/upload")
    @ApiOperation("上传文件")
    public R upload(@RequestParam("file") MultipartFile file){
        return saveFile(file);
    }
    @PostMapping("/multiUpload")
    public R multiUpload(@RequestParam("file")MultipartFile[] files){
        System.out.println("文件的个数:"+files.length);
        for (MultipartFile f : files){
            saveFile(f);
        }
        return R.ok();
    }


    private R saveFile(MultipartFile file){
        if (file.isEmpty()){
            return R.error("未选择文件！");
        }

        String uuid = UUID.randomUUID().toString();
        String filename =   uuid +"."+ file.getOriginalFilename().split("\\.")[1];
        File temp = new File(filePath);
        if (!temp.exists()){
            temp.mkdirs();
        }

        File localFile = new File(filePath+"/img/"+filename);
        try {
            //把上传的文件保存至本地
            file.transferTo(localFile);
            System.out.println(file.getOriginalFilename()+" 上传成功");
        }catch (IOException e){
            e.printStackTrace();
            return R.error("上传失败");
        }

        return R.ok().put("data",filename);
    }
}
